package com.lp.model.exception;

import com.lp.model.config.AppResult;
import com.lp.model.config.CodeMsg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 统一异常处理
 */
@Slf4j
@ControllerAdvice
public class HandlerException {

    /**
     * 捕捉自定义异常
     */
    @ExceptionHandler(ApplicationException.class)
    @ResponseBody
    public AppResult applicationException(ApplicationException e) {
        e.printStackTrace();
        log.error(e.getMessage());
        if(e.getErrResult() != null) {
            return e.getErrResult();
        }
        return AppResult.fail(e.getMessage());
    }

    /**
     * 捕捉非自定义异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public AppResult exception(Exception e) {
        e.printStackTrace();
        if(!StringUtils.hasLength(e.getMessage())) {
            return AppResult.fail(CodeMsg.FAIL);
        }
        log.error(e.getMessage());
        return AppResult.fail(e.getMessage());
    }

}
